package com.qianchang.microfinance.view.login;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.provider.Settings;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.TokenManager;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DMLog;
import com.dm.library.utils.FormatUtil;
import com.dm.library.utils.MD5Util;
import com.dm.library.utils.PackageUtils;
import com.dm.library.utils.StringUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.RoundImageView;
import com.dm.library.widgets.element.DButton;
import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.statusbar.StatusBarUtil;
import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.DeviceTokenBean;
import com.qianchang.microfinance.bean.UserLoginInfo;
import com.qianchang.microfinance.bean.event.LoginEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.setting.SettingTradPasswordActivity;
import com.qianchang.microfinance.utils.APKUtils;
import com.qianchang.microfinance.utils.AppManager;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.utils.IdentifyCode;
import com.qianchang.microfinance.view.MainActivity;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.register.RegisterActivity;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qianchang.microfinance.R.id.tv_back;


/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述: <描述>
 * 修 改 人: sushuo
 * 修改时间: 2017-1-16
 */

public class LoginActivity extends BaseActivity {

    private static final String TAG = "LoginActivity";
    @BindView(R.id.et_input_account)
    EditText etInputAccount;
    @BindView(R.id.et_input_password)
    EditText etInputPassword;
    @BindView(R.id.iv_pwd_visible)
    CheckBox ivPwdVisible;
    @BindView(R.id.ll_checkcode)
    LinearLayout llCheckcode;

    @BindView(R.id.tv_login)
    DButton tvLogin;
    @BindView(R.id.tv_register)
    DTextView tvRegister;
    @BindView(R.id.tv_forget_pwd)
    DTextView tvForgetPwd;
    @BindView(R.id.et_input_checkcode)
    EditText etInputCheckcode;
    @BindView(R.id.ll_identify_code)
    LinearLayout llIdentifyCode;
    @BindView(R.id.iv_checkcode)
    RoundImageView ivCheckcode;
//    @BindView(tv_back)
//    DTextView tvBack;
    @BindView(R.id.tv_title)
    DTextView tvTitle;
    private long mExitTime = 0;
    private boolean needShowCode;//登录三次后显示验证码

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        StatusBarUtil.setTranslucentForImageViewInFragment(LoginActivity.this, null);
        ButterKnife.bind(this);
        initView();
        initData();
        showIdentifyCode();//test
    }

    @Override
    protected void initView() {
        super.initView();
        tvTitle.setText(getString(R.string.Label_login));
//        Drawable drawable = getResources().getDrawable(R.drawable.exit);
//        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
//        tvBack.setCompoundDrawables(drawable, null, null, null);
        ivPwdVisible.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                int length = etInputPassword.getText().length();
                if (isChecked) {
                    etInputPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    etInputPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                etInputPassword.setSelection(length);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        PackageUtils.closeKey(this);
    }


    @Override
    protected void initData() {
        super.initData();

        try {

//            String phone = DMApplication.getInstance().getmUserLoginInfo().getPhone();
            String phone = "";
            UserLoginInfo userLoginInfo = DMApplication.getInstance().getmUserLoginInfo();
            if(userLoginInfo != null){
                phone = userLoginInfo.getPhone();
            }
            if (phone != null && (!phone.equals("")) && phone.length() > 1) {
                etInputAccount.setText(phone);
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        //从注册界面跳转时获取手机号码
        insertPhoneFromRegister();
    }

    private void insertPhoneFromRegister() {
        Intent intent = getIntent();
        if (intent != null) {
            String phone = intent.getStringExtra(RegisterActivity.KEY_PHONE);
            if (!StringUtils.isEmptyOrNull(phone)) {
                etInputAccount.setText(phone);
            }
        }
    }

    @OnClick({R.id.iv_checkcode, R.id.tv_login, R.id.tv_register, R.id.tv_forget_pwd, R.id.tv_back})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_checkcode://更新验证码
                showIdentifyCode();
                break;
            case R.id.tv_login://登陆
                checkAndLogin();
                break;
            case R.id.tv_register://register
                startActivity(RegisterActivity.class);            //2018.1.18注释迪蒙的
                //startActivity(RegisterActivity.class, true);         //2018.1.18鸿胜修改为自己功能的 注册
                break;
            case R.id.tv_forget_pwd://忘记密码
                Intent intent = new Intent(LoginActivity.this, ForgetActivityOne.class);
                intent.putExtra(SettingTradPasswordActivity.IS_TRAD_PWD, false);
                startActivity(ForgetActivityOne.class);
                break;
            case R.id.tv_back:
                 EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGIN_FAILED));
//                EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGIN_SUC));
                System.exit(0);


                break;
        }
    }


    //更新验证码 并显示
    private void showIdentifyCode() {
        ivCheckcode.setImageBitmap(IdentifyCode.getInstance(this).createBitmap());
    }

    //校验并登陆
    private void checkAndLogin() {
        String strAccount = etInputAccount.getText().toString().trim();
        String strPwd = etInputPassword.getText().toString().trim();

        if (StringUtils.isEmptyOrNull(strAccount)) {
            ToastUtil.getInstant().show(LoginActivity.this, getString(R.string.msg_please_input_phone_number));
            return;
        }
        if (!FormatUtil.isValidPhone(strAccount, null)) {
            ToastUtil.getInstant().show(LoginActivity.this, getString(R.string.msg_input_correct_account));
            return;
        }
        if (StringUtils.isEmptyOrNull(strPwd)) {
            ToastUtil.getInstant().show(LoginActivity.this, getString(R.string.msg_please_input_pwd));
            return;
        }
        if (!FormatUtil.isValidPassword(strPwd, null)) {
            ToastUtil.getInstant().show(LoginActivity.this, getString(R.string.msg_pwd_length_too_short));
            return;
        }
        //通过后登录
        login(strAccount, strPwd);
    }

    //登录
    private void login(final String strAccount, final String strPwd) {
        show();
        HttpParams params = new HttpParams();
        params.put("appqmjloginAccount", strAccount);
        params.put("appqmjpassword", MD5Util.string2MD5(strPwd + ConstantAppInfo.Password.PASSWORD_SUFFIX));
        params.put("appqmjversion", APKUtils.getVerName(getApplicationContext()));

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.LOGIN, params, new RequestCallBack<UserLoginInfo>() {//UserLoginInfo
            @Override
            public void onSuccess(JsonResult<UserLoginInfo> response) {
                dismiss();
                setIdentifyCodeGone();//显示隐藏 验证码
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    UserLoginInfo userLoginInfo = response.getObject();
                    loginSuccess(userLoginInfo);

                    setOnProfileSignIn(userLoginInfo.getUserId());
                    updateDeviceToken();        //上传友盟推送DeviceToken

                } else {
                    ToastUtil.getInstant().show(LoginActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(LoginActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }
        });
    }


    private void setIdentifyCodeGone() {
        if (!needShowCode) {
            needShowCode = false;
            llIdentifyCode.setVisibility(View.GONE);
        }
    }

    /***
     * 登录成功
     */
    private void loginSuccess(UserLoginInfo userLoginInfo) {
        Log.i("wmy", "登录成功 = " + userLoginInfo.getUserId() + " " + userLoginInfo.getToken() + " " + userLoginInfo.getUserName());
        DMApplication.getInstance().setUserLoginInfo(userLoginInfo);
        TokenManager.getInstance().setToken(LoginActivity.this, userLoginInfo.getToken());
        EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGIN_SUC));
        startActivity(MainActivity.class, true);
    }


    /*****
     * 上传友盟推送 device_token
     */

    private void updateDeviceToken(){

        show();
        String deviceToken = TokenManager.getInstance().getDeviceToken(getApplicationContext());
        HttpParams params = new HttpParams();
        params.put("deviceToken",deviceToken);

        DMOKHttpUtils.getInstance().post(getApplicationContext(), DMConstant.ApiURL.UPDATE_DEVICE_TOKEN, params, new RequestCallBack<DeviceTokenBean>() {
            @Override
            public void onSuccess(JsonResult<DeviceTokenBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    DMLog.e("DeviceToken response==============" + response);

                } else {
                    ToastUtil.getInstant().show(LoginActivity.this, response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(LoginActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {
                dismiss();
            }
        });
    }

    //设置用友盟统计自身账号登录
    private void setOnProfileSignIn(String Id){
        if(Id != null && (!Id.equals(""))){
            MobclickAgent.onProfileSignIn(Id);
        }
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //按两次返回退出应用程序
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
////            System.exit(0);
////            EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGOUT));
//            return true;
//        }

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            AppManager.getAppManager().AppExit(this);
            LoginActivity.this.finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


}
